<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\models\system\AdminPos;
use common\models\system\Position;
use common\services\PermissionService;

class PositionService
{
    /**
     * 获取某个用户的岗位列表
     * @param string|int $userId
     * @return array
     */
    public static function selectPositionByUserId($userId): array
    {
        if (!$userId) return [];
        $list = Position::find()->alias('p')->select(['p.id', 'p.name', 'p.pos_key', 'p.status', 'p.list_sort'])
            ->leftJoin(AdminPos::tableName() . ' up', 'up.pos_id = p.id')
            ->where(['up.admin_id' => $userId])
            ->orderBy('p.list_sort asc, p.id asc')->distinct()->asArray()->all();
        return $list ?: [];
    }

    /**
     * 某个用户可选择列表
     * @param $userId
     * @return array
     */
    public static function selectUserPositionSelectList($userId): array
    {
        if(PermissionService::isAdmin($userId)) return self::getList();
        return self::selectPositionByUserId($userId);
    }

    /**
     * 获取岗位列表
     * @param bool $all
     * @return array
     */
    public static function getList($all = true): array
    {
        $list = Position::find()->select(['id', 'name', 'pos_key','status']);
        if (!$all) $list = $list->where(['status' => 1]);
        $list = $list->orderBy('list_sort asc, id asc')->asArray()->all();
        return $list ?: [];
    }

    /**
     * 检测某个用户是否有某个岗位
     * @param string|integer $userId
     * @param string|integer $postId
     * @return bool
     */
    public static function checkHasPositionPerm($userId, $postId): bool
    {
        if (PermissionService::isAdmin($userId)) return true;
        if (!$userId || !$postId) return false;
        $postList = self::selectUserPositionSelectList($userId);
        foreach ($postList as $post) {
            if ($post['id'] == $postId && $post['status'] == '1') return true;
        }
        return false;
    }
}
